import { chromium } from 'playwright';
import type  { Browser, Page, BrowserContext } from 'playwright';
import {LoginPage} from "../GPO_Page_Object/login_page.ts";
import {FirstPage} from "../GPO_Page_Object/first_page.ts";

export async function openBrowser(url: string, headless: boolean) {
    console.log('openBrowser called with url:', url, 'headless:', headless);
    const browser = await chromium.launch({
        headless: !headless,
        args: ['--start-maximized'],
        executablePath: 'C:\\Program Files (x86)\\Microsoft\\Edge\\Application\\msedge.exe'
    });
    console.log('Browser launched:', !!browser);
    if (!browser) {
        throw new Error("Playwright browser instance hasn't been initialized yet.");
    }
    const context = await browser.newContext({ viewport: null });
    const page = await context.newPage();
    return {browser, page, context}
}

export async function loginGPO (url:string, isHeadless:boolean){
    console.log('Starting login with headless:', isHeadless);
    const { browser, page, context }: { browser: any, page: Page, context: any } = await openBrowser(url, isHeadless)
    const login = new LoginPage(page)
    await login.GPOOpen(url)
    await login.singleSignOn()
    return {browser, page, context}
}

export async function orderListEntry(_event:any, url:string, isHeadless:boolean){
    const { browser, page, context }: { browser: Browser, page: Page, context: BrowserContext } = await loginGPO(url, isHeadless)
    const first = new FirstPage(page)
    first.orderListEntry()
    return {browser, page, context}
}

export async function reportListEntry(_event:any, url:string, isHeadless:boolean){
    const { browser, page, context }: { browser: Browser, page: Page, context: BrowserContext } = await loginGPO(url, isHeadless)
    const first = new FirstPage(page)
    first.reportListEntry()
    return {browser, page, context}
}